package br.ufal.tci.nexos.arcolive;

import java.net.InetAddress;

import br.ufal.tci.nexos.arcolive.exception.ArCoLIVECannotStartServerSocketException;
import br.ufal.tci.nexos.arcolive.logger.ArCoLIVELogRepository;
import br.ufal.tci.nexos.arcolive.logger.ArCoLIVELogger;
import br.ufal.tci.nexos.arcolive.service.broker.ArCoLIVEServiceBroker;
import br.ufal.tci.nexos.arcolive.service.connection.ArCoLIVEConnectionManager;

public class Main {
	public static void main(String[] args) {
		ArCoLIVEServiceManager serviceManager = ArCoLIVEServiceManager
				.getInstance();
		ArCoLIVEConnectionManager connectionManager = ArCoLIVEConnectionManager
				.getInstance();
		ArCoLIVEServiceBroker serviceBroker = ArCoLIVEServiceBroker
				.getInstance();
		ArCoLIVELogRepository logRepository = ArCoLIVELogRepository
				.getInstance();
		ArCoLIVEServerProperties serverProperties = ArCoLIVEServerProperties
				.getInstance();

		ArCoLIVELogger logger = new ArCoLIVELogger();
		logRepository.addListener(logger);
		if (serviceManager == null) {
			logRepository
					.log("Error while loading the Service Manager. Try to check the persistence.implementationImpl value in the configuration file");
		}

		// start available services and its each instance
		try {
			serviceManager.loadServices();
		} catch (Exception e) {
			logRepository.log("Erro while loading services: " + e.getMessage());
			e.printStackTrace();
			System.exit(0);
		}

		/*
		 * //just for tests proporse String locationUrl =
		 * "file://My/MyProjects/videos/a.mpg"; //String locationUrl = "v4l://";
		 * ConferenceOneToMany alConference = new ConferenceOneToMany("Teste de
		 * videoconfer?ncia", "Testando o servidor de confer?ncia", 5, 40000,
		 * new MediaLocator(locationUrl), null);
		 * serviceManager.addNewServiceInstance(700, alConference);
		 * 
		 * try { alConference.startService(); } catch
		 * (ArCoLIVECannotStartServiceException e) { e.printStackTrace(); }
		 */

		int port = serverProperties.getIntProperty("server.port");
		connectionManager.setPort(port);
		connectionManager.setListener(serviceBroker);
		try {
			connectionManager.startListen();
			InetAddress serverInetAddress = connectionManager
					.getListenInetAddress();
			logRepository.log("Server "
					+ serverProperties.getStringProperty("server.name")
					+ " started and listening on "
					+ serverInetAddress.getHostAddress() + ":" + port + ". ("
					+ serviceManager + ")");
		} catch (ArCoLIVECannotStartServerSocketException e) {
			logRepository.log("Erro while loading services: " + e.getMessage());
			System.exit(0);
		}

	}
}
